package com.whccb.apps.office.document.event.receive;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.ODAppUtil;

/**
 * 
 * 收文流程行长审批后，将审批记录同步至子流程，并发送通知
 * 
 * @author xqli
 * 
 */
public class BankleaderOpinionToSubProcessAndNotifyEvent_bak extends
		ExecuteListener implements ExecuteListenerInterface {
	public String getDescription() {
		return "收文流程行长审批后，将签批意见同步至子流程，并发送通知.";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	@Override
	public void execute(ProcessExecutionContext pec) throws Exception {
		String parentBindid = pec.getProcessInstance().getId();
		List<ProcessInstance> subProcessList = SDK.getProcessAPI().query()
				.parentProcessInstId(pec.getProcessInstance().getId()).list();
		BO parentBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE",
				parentBindid);
		String parentDCGroupValue = parentBindid;
		String parentDCFileValue = parentBo.getId();
		Map<String, String> leaderSignMap = null;
		String queryParentHwSql = " SELECT ID,BINDID,BOID,APPID,BOITEMNAME,TASKINSTID,CREATEUSER,CREATETIME,FILENAME,SIGNUSER,SIGNTIME,NOWTYPE,DATA,QRCODE,USERMZ,SORT FROM APP_ACT_HWSIGNATURE_DATA WHERE BINDID = :BINDID AND BOITEMNAME = :BOITEMNAME ";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("BINDID", parentBindid);
		paramMap.put("BOITEMNAME", "LEADERSIGN");
		List<Map<String, String>> leaderSignList = DBSql.query(
				queryParentHwSql, paramMap,
				new RowMapper<Map<String, String>>() {
					public Map<String, String> mapRow(ResultSet rs, int index)
							throws SQLException {
						Map<String, String> map = new HashMap<String, String>();
						map.put("ID", rs.getString("ID"));
						map.put("BINDID", rs.getString("BINDID"));
						map.put("BOID", rs.getString("BOID"));
						map.put("APPID", rs.getString("APPID"));
						map.put("BOITEMNAME", rs.getString("BOITEMNAME"));
						map.put("TASKINSTID", rs.getString("TASKINSTID"));
						map.put("CREATEUSER", rs.getString("CREATEUSER"));
						map.put("CREATETIME", rs.getString("CREATETIME"));
						map.put("FILENAME", rs.getString("FILENAME"));
						map.put("SIGNUSER", rs.getString("SIGNUSER"));
						map.put("SIGNTIME", rs.getString("SIGNTIME"));
						map.put("NOWTYPE", rs.getString("NOWTYPE"));
						map.put("DATA", "");
						map.put("QRCODE", "");
						map.put("USERMZ", "");
						map.put("SORT", "");
						return map;
					}
				});

		if (leaderSignList != null && !leaderSignList.isEmpty()
				&& leaderSignList.size() > 0) {
			leaderSignMap = leaderSignList.get(0);
		}

		if (leaderSignMap != null && !leaderSignMap.isEmpty()) {
			// 构建父流程的签批DC，将其复制到子流程相应位置。
			DCContext parentLeaderDc = new DCContext(pec.getUserContext(), SDK
					.getDCAPI().getDCProfile(
							"com.actionsoft.apps.formui.hwsignature",
							"-hsingature-"), ODConstant.APP_ID,
					parentDCGroupValue, parentDCFileValue,
					leaderSignMap.get("FILENAME"));
			if (parentLeaderDc != null && subProcessList != null
					&& !subProcessList.isEmpty() && subProcessList.size() > 0) {
				for (ProcessInstance subProcess : subProcessList) {
					if (subProcess != null) {
						BO subBo = SDK.getBOAPI().getByProcess(
								"BO_WHBK_OD_RECEIVE_DO", subProcess.getId());

						// 插入签批表APP_ACT_HWSIGNATURE_DATA数据
						JSONObject insertParamMap = new JSONObject();
						insertParamMap.put("ID", UUIDGener.getUUID());
						insertParamMap.put("BINDID", subProcess.getId());// 子流程实例ID
						insertParamMap.put("BOID", subBo.getId());// 子流程的BO记录ID
						insertParamMap.put("APPID", leaderSignMap.get("APPID"));
						insertParamMap.put("BOITEMNAME", "LEADERSIGN");
						insertParamMap.put("TASKINSTID",
								subProcess.getStartTaskInstId());
						insertParamMap.put("CREATEUSER",
								leaderSignMap.get("CREATEUSER"));
						insertParamMap.put("CREATETIME",
								leaderSignMap.get("CREATETIME"));
						insertParamMap.put("FILENAME",
								leaderSignMap.get("FILENAME"));
						insertParamMap.put("SIGNUSER",
								leaderSignMap.get("SIGNUSER"));
						insertParamMap.put("SIGNTIME",
								leaderSignMap.get("SIGNTIME"));
						insertParamMap.put("NOWTYPE",
								leaderSignMap.get("NOWTYPE"));
						insertParamMap.put("DATA", "");
						insertParamMap.put("QRCODE", "");
						insertParamMap.put("USERMZ", "");
						insertParamMap.put("SORT", "");
						// 调用App
						String sourceAppId = "com.actionsoft.apps.formui.hwsignature";
						// aslp服务地址
						String aslp = "aslp://com.actionsoft.apps.formui.hwsignature/saveHwData";
						// 参数定义列表
						Map<String, Object> params = new HashMap<String, Object>();
						// 手写签批json信息，不允许空值,必填
						params.put("hwjson", insertParamMap.toString());
						// 插入手写签批数据库记录
						ResponseObject ro = SDK.getAppAPI().callASLP(
								SDK.getAppAPI().getAppContext(sourceAppId),
								aslp, params);
						// 复制签批DC
						String subDCGroupValue = subProcess.getId();
						String subDCFileValue = subBo.getId();
						DCContext subLeaderDc = new DCContext(
								pec.getUserContext(),
								SDK.getDCAPI()
										.getDCProfile(
												"com.actionsoft.apps.formui.hwsignature",
												"-hsingature-"),
								ODConstant.APP_ID, subDCGroupValue,
								subDCFileValue, leaderSignMap.get("FILENAME"));
						subLeaderDc.delete();
						SDK.getDCAPI().copyDCFile(parentLeaderDc, subLeaderDc);
						sendNotify(subProcess.getId(), parentBo);
					}
				}
			}
		}
	}

	private void sendNotify(String subBinid, BO swBo) {
		if (StringUtils.isNotEmpty(subBinid) && swBo != null) {
			// 得到子流程的第一节点办理人，即为任务提醒人
			String notifyUserid = "";
			String subTaskId = "";
			List<TaskInstance> taskList = SDK.getTaskAPI().query()
					.activityDefId(ODConstant.SWBL_TASK_DEFID)
					.processInstId(subBinid).list();
			if (taskList != null && !taskList.isEmpty() && taskList.size() > 0) {
				notifyUserid = taskList.get(0).getTarget();
				subTaskId = taskList.get(0).getId();
			} else {
				List<HistoryTaskInstance> taskHisList = SDK.getTaskAPI()
						.queryHistory()
						.activityDefId(ODConstant.SWBL_TASK_DEFID)
						.processInstId(subBinid).list();
				if (taskHisList != null && !taskHisList.isEmpty()
						&& taskHisList.size() > 0) {
					notifyUserid = taskHisList.get(0).getTarget();
					subTaskId = taskHisList.get(0).getId();
				}
			}

			// 发送通知
			JSONObject json = new JSONObject();
			StringBuffer notifycontent = new StringBuffer();
			notifycontent.append("来文机构:").append(swBo.getString("RECEIVEORG"))
					.append(",文号为：").append(swBo.getString("FILENUM"))
					.append("的收文流程，行长有最新的批示，请及时查阅！");
			json.put("notifycontent", notifycontent.toString());
			json.put("bindid", subBinid);
			json.put("taskid", subTaskId);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("sender", "admin");
			params.put("targetIds", notifyUserid);
			params.put("content", json.toString());
			params.put("systemName", ODConstant.NOTIFY_SYSNAME);
			ODAppUtil.sendOfficeDocumentNotification(params);
		}
	}
}
